""" 
Created the 2013-08-26 11:56 

@author:
"""
from libatomism import *
from xml.dom import minidom

class msXmlLoader( msTreeMapper ):
    """
    myclass documentation
    """
    def __init__(self):
        super( msXmlLoader , self).__init__()
        
    def initialize(self):
        """ declare and initialize childs and attributes of the object.
        See msTreeMapper documentation.
        """
        super(msXmlLoader, self).initialize()
        # add your declarations
     
    def update(self):
        
        """ update childs and attributes of the object, when then internal
        state of self is changed.
        See msTreeMapper documentation.
        """
        super(msXmlLoader, self).update()
        # update your variables
        
    @staticmethod
    def New(  ):
        """
        New(  ) -> msTreeMapper
        method New documentation
        
        """
        Self = msXmlLoader()
        Self.initialize()
        Self.update()
        return Self
   
    def open(self,mapper,filename):
        """
        open(  (msXmlWritte) self , (msTreeMapper)  arg1, (string) arg2 ) -> void.

        save in a file the node given 
        arg1: node to print 
        arg2: filename
        """
        
        doc = minidom.parse(filename)
        node =  doc.childNodes[0]
        attributes = mapper.getAttributes()
        
        for att in attributes:
            id = att.split('=')[0][:-1]
            mapper.setAttribute(id ,str(node.getAttribute(id)))
        self.listSymLink=[]
        self.__createNode( mapper, node) 
        mapper.update()
        self.root = mapper
        
        for symlink in self.listSymLink:
            symlink[0].replaceChild( self.getObject( symlink[0], symlink[2] ) ,str( symlink[1] ) )

        self.__updateAll( self.root)
 
    def __updateAll(self, parent):

        for child in parent.getChildren():
            self.__updateAll(child)
        parent.update()

    def __createNode(self, parent, xmlnode):

        for xmlChild in xmlnode.childNodes:
            try:
                vartype = xmlChild.tagName.split('-')[0]
                varname = xmlChild.tagName.split('-')[1]
        
                if( not (xmlChild.getAttribute("PointerTo") == "" ) ):
                    self.listSymLink.append( (parent, varname, xmlChild.getAttribute("PointerTo") ))
                    child = self.__newObject(xmlChild,parent)
                    parent.addChild(child,str(varname))
                
                if( xmlChild.getAttribute("PointerTo") == "" ):
                    if( not parent.hasChildOfName(str(varname))):
                        try:
                            child = self.__newObject(xmlChild,parent)
                            try:
                                parent.addChild(child,str(varname))
                            except:
                                pass
                        except:
                            raise("can not create new object")
                    else:
                        child = parent.getChild(str(varname))
                
                    attributes = child.getAttributes()
                    for att in attributes:
                        id = att.split('=')[0][:-1]
                        child.setAttribute(id ,str(xmlChild.getAttribute(id)))
                    self.__createNode(child,xmlChild)
            except:
                pass

    def getObject( self,  parent, path):

        node = self.root
        for elem in path.split("/")[2:]:
            if( elem==".."):
                node = node.getParent()
            elif(elem!=""):
                node = node.getChild(str(elem))
        return node
        
    def __newObject(self, xmlchild,parent):
        child = 0
        try:
            child = globals()[ xmlchild.tagName.split('-')[0] ]()
        except:
            pass
        try:
            child = globals()[ xmlchild.tagName.split('-')[0] ].New()
        except:
            pass
        try:
            child = globals()[ xmlchild.tagName.split('-')[0] ].New("")
        except:
            pass

        try:
            units = msUnitsManager.New("")
            child = globals()[ xmlchild.tagName.split('-')[0] ].New(units)
            units.setAffiliation(child)
        except:
            pass    

        return child
